package com.cstp.manage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.cstp.exception.ServiceException;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @author watts
 */
@Component
public class FileManage {

    @Value("${upload.file.path:/opt/cstp/upload/}")
    private String uploadPath;

    @SneakyThrows
    public String uploadReportResource(List<MultipartFile> files) {
        List<String> filePaths = Lists.newArrayList();
        String dirPath = LocalDate.now().toString() + "/";
        FileUtil.mkdir(uploadPath + dirPath);
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                throw new ServiceException("上传文件失败");
            }
            byte[] bytes = file.getBytes();
            String fPath = dirPath + UUID.randomUUID() + "." + FileNameUtil.getSuffix(file.getOriginalFilename());
            Path path = Paths.get(uploadPath + fPath);
            Files.write(path, bytes);
            filePaths.add(fPath);
        }
        return String.join(";", filePaths);
    }
}
